//
//  PriceQueryViewController.m
//  WorkNest
//
//  Created by qbm360 on 15/7/8.
//  Copyright (c) 2015年 nest. All rights reserved.
//

#import "PriceQueryViewController.h"
#import "PriceQueryChooseViewController.h"
#import "ImageAddingView.h"

@interface PriceQueryViewController () <UIImagePickerControllerDelegate>

@property (strong, nonatomic) NSArray *array;
@property (strong, nonatomic) ImageAddingView *imageAdding;
@property (strong, nonatomic) PriceQueryModel *priceQueryModel;
@property (assign, nonatomic) NSInteger index;
@property (strong, nonatomic) NSMutableArray *idArray;

@end

@implementation PriceQueryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = _priceTitle;
    _array = @[@[@"定制产品名称",@"产品是否有样衣",@"面辅料",@"面辅料备注"],@[@"商品吊牌",@"包装",@"要求样衣交付时间",@"预计大货下单时间",@"预计每次订单件数",@"打样前是否选主面料"],@[@"产品链接",@"产品详细说明"]];
    [self tableFootview];
    self.priceQueryModel = [[PriceQueryModel alloc] init];
    if (!_detailArray) {
        _detailArray = @[@[@"",@"否",@"包工包料",@""],@[@"委托采购",@"委托采购",@"",@"",@"",@"是"],@[@"",@""]];
        _priceQueryModel.isProductSPL = @"0";
        _priceQueryModel.accessory = @"10";
        _priceQueryModel.mark = @"22";
        _priceQueryModel.pack = @"32";
        _priceQueryModel.isChoiceMainfabric = @"1";
    } else {
        self.priceQueryModel = _model;
    }
    self.imageAdding = [[ImageAddingView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 70)];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIUtil colorWithHexString:appFontColor]}];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)tableFootview {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"submitButton"] forState:UIControlStateNormal];
    [button setTitle:@"提交" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.frame = CGRectMake((SCREEN_WIDTH-74)/2, 8, 74, 32);
    [button addTarget:self action:@selector(submitImage) forControlEvents:UIControlEventTouchUpInside];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 48)];
    [view addSubview:button];
    self.tableView.tableFooterView = view;
}

- (void)submitImage {
    [ESHUDView showLoading];
    _idArray = [NSMutableArray arrayWithCapacity:self.imageAdding.imageDatas.count];
    if (self.imageAdding.imageDatas.count > 0) {
        for (int i = 0; i < self.imageAdding.imageDatas.count; i++) {
            if (i==0) {
                dispatch_queue_t queue = dispatch_queue_create("QuDetailQueue", DISPATCH_QUEUE_SERIAL);
                dispatch_async(queue, ^{
                    [self uploadFile:self.imageAdding.imageDatas[i]];
                });
            } else {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        [self uploadFile:self.imageAdding.imageDatas[i]];
                    });
                });
            }
        }
    } else {
        [self submit];
    }
}

- (void)uploadFile:(UIImage *)imageData {
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken};
    [RequestData fileUploadParameters:[UIUtil toJsonString:dic] imageData:imageData withBlock:^(NSString *fileId, NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"图片上传失败":msg dismissBlock:nil];
            }
            [[AFAPIClient sharedClient].operationQueue cancelAllOperations];
        } else {
            self.index = self.index +1;
            NSLog(@"%ld",(long)self.index);
            [_idArray addObject:fileId];
//            self.priceQueryModel.imageList = _idArray;
            if (self.idArray.count == self.imageAdding.imageDatas.count) {
                [self submit];
            }
        }
    }];
}

- (void)submit {
    [ESHUDView showLoading];
    if ([self.priceTitle isEqualToString:@"询价单"]) {
        self.priceQueryModel.cellPhone = [UserModel sharedInstance].userName;
        NSDictionary *modelDic = self.priceQueryModel.keyValues;
        if ([self.priceQueryModel.productDetailRequire isEqualToString:@""] || [self.priceQueryModel.inquireProductName isEqualToString:@""] || !self.priceQueryModel.productDetailRequire || !self.priceQueryModel.inquireProductName) {
            [[ESHUDView sharedInstance] showErrorMessage:@"产品名称和说明不能为空" dismissBlock:nil];
            return;
        }
        NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken, @"inquire":modelDic, @"imageList":self.idArray};
        [RequestData priceQueryParameters:[UIUtil toJsonString:dic] withBlock:^(NSString *needId, NSString *msg, NSError *error) {
            if (error) {
                if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                    [UIUtil tokenOverdue:self msg:msg];
                } else {
                    [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"提交询价单失败":msg dismissBlock:nil];
                }
            } else {
                [[ESHUDView sharedInstance] showSuccessMessage:msg dismissBlock:nil];
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    } else {
        if ([self.priceQueryModel.productDetailRequire isEqualToString:@""] || [self.priceQueryModel.developProductName isEqualToString:@""] || !self.priceQueryModel.productDetailRequire || !self.priceQueryModel.developProductName) {
            [[ESHUDView sharedInstance] showErrorMessage:@"产品名称和说明不能为空" dismissBlock:nil];
            return;
        }
        NSDictionary *modelDic = self.priceQueryModel.keyValues;
        NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken, @"need":modelDic, @"imageList":self.idArray};
        [RequestData developParameters:[UIUtil toJsonString:dic] withBlock:^(NSString *inquireId, NSString *msg, NSError *error) {
            if (error) {
                if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                    [UIUtil tokenOverdue:self msg:msg];
                } else {
                    [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"提交制版打样失败":msg dismissBlock:nil];
                }
            } else {
                [[ESHUDView sharedInstance] showSuccessMessage:msg dismissBlock:nil];
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0: {
            return 4;
        }
        case 1: {
            return 6;
        }
        case 2: {
            return 2;
        }
        case 3: {
            return 1;
        }
        default:
            return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section != 3) {
        static NSString *priceCellIdentifier = @"PriceCell";
        UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:priceCellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:priceCellIdentifier];
            [cell.textLabel setFont:[UIFont systemFontOfSize:14]];
            [cell.detailTextLabel setFont:[UIFont systemFontOfSize:14]];
        }
        if ((indexPath.section == 0 && indexPath.row == 0) || (indexPath.section == 2 && indexPath.row == 1)) {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, 10 , 10)];
            label.textColor = [UIColor redColor];
            label.text = @"*";
            label.font = [UIFont systemFontOfSize:15];
            [cell addSubview:label];
        }
        cell.textLabel.text = [NSString stringWithFormat:@"  %@",[[_array objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
        cell.detailTextLabel.text = [[_detailArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
        [cell.textLabel setTextColor:[UIUtil colorWithHexString:appFontColor]];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        if (indexPath.section == 1 && indexPath.row == 4) {
            cell.hidden = [self.priceTitle isEqualToString:@"询价单"] ? NO : YES;
        }
        if (indexPath.section == 1 && indexPath.row == 2) {
            cell.hidden = [self.priceTitle isEqualToString:@"询价单"] ? YES : NO;
        }
        return cell;
    } else {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        [cell addSubview:self.imageAdding];
        if (_imageList.count>0) {
            _imageAdding.imageDatas = _imageList;
        }
        if (self.priceQueryModel.imageList.count >0) {
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self.priceQueryModel.imageList count]];
            for (NSString *url in self.priceQueryModel.imageList) {
                UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
                [array addObject:image];
            }
            _imageAdding.imageDatas = array;
        }
        __weak __typeof(&*self)weakSelf = self;
        self.imageAdding.backColor = [UIUtil colorWithHexString:@"#ffffff"];
        self.imageAdding.imagePickerBlock = ^(UIViewController *picker) {
            [weakSelf.navigationController presentViewController:picker animated:YES
                                                      completion:nil];
        };
        return cell;
    }
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PriceQueryChooseViewController *chooseView = [[PriceQueryChooseViewController alloc] init];
    if (indexPath.section != 3) {
        if ((indexPath.section == 0 && indexPath.row == 0) || (indexPath.section == 2 && indexPath.row == 0) || (indexPath.section == 1 && indexPath.row == 2) || (indexPath.section == 1 && indexPath.row == 3) || (indexPath.section == 1 && indexPath.row == 4))  {
            chooseView.choose = @"0";
        } else if ((indexPath.section ==0 && indexPath.row == 3) || (indexPath.section == 2 && indexPath.row == 1)) {
            chooseView.choose = @"1";
        }
        chooseView.positionArray = @[[NSString stringWithFormat:@"%ld",(long)indexPath.section], [NSString stringWithFormat:@"%ld",(long)indexPath.row], [NSString stringWithFormat:@"%@",[[_array objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]]];
        chooseView.detailText = [self.tableView cellForRowAtIndexPath:indexPath].detailTextLabel.text;
        [self.navigationController pushViewController:chooseView animated:YES];
        chooseView.chooseBlock = ^(NSString *title) {
            [self modelWithIndexPath:indexPath content:title];
            [self.tableView cellForRowAtIndexPath:indexPath].detailTextLabel.text = title;
        };
    }
}

- (void)modelWithIndexPath:(NSIndexPath *)indexPath content:(NSString *)content {
    NSMutableArray *array = [NSMutableArray arrayWithArray:_detailArray];
    NSMutableArray *replaceArray = [NSMutableArray arrayWithArray:[array objectAtIndex:indexPath.section]];
    [replaceArray replaceObjectAtIndex:indexPath.row withObject:content];
    [array replaceObjectAtIndex:indexPath.section withObject:replaceArray];
    _detailArray = array;
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0: {
                if ([self.priceTitle isEqualToString:@"询价单"]) {
                    self.priceQueryModel.inquireProductName = content;
                } else {
                    self.priceQueryModel.developProductName = content;
                }
                break;
            }
            case 1: {
                self.priceQueryModel.isProductSPL = [content isEqualToString:@"是"]?@"1":@"0";
                break;
            }
            case 2: {
                self.priceQueryModel.accessory = content.length==2?@"19":content.length==3?@"11":content.length==4?@"10":@"12";
                break;
            }
            case 3: {
                self.priceQueryModel.remark = content;
                break;
            }
            default:
                break;
        }
    }
    if (indexPath.section == 1) {
        switch (indexPath.row) {
            case 0: {
                if ([content isEqualToString:@"我提供"]) {
                    self.priceQueryModel.mark = @"20";
                } else if ([content isEqualToString:@"不需要"]) {
                    self.priceQueryModel.mark = @"21";
                } else if ([content isEqualToString:@"委托采购"]) {
                    self.priceQueryModel.mark = @"22";
                }
                break;
            }
            case 1: {
                if ([content isEqualToString:@"我提供"]) {
                    self.priceQueryModel.pack = @"30";
                } else if ([content isEqualToString:@"不需要"]) {
                    self.priceQueryModel.pack = @"31";
                } else if ([content isEqualToString:@"委托采购"]) {
                    self.priceQueryModel.pack = @"32";
                }
                break;
            }
            case 2: {
                self.priceQueryModel.splDeliveryTime = content;
                break;
            }
            case 3: {
                self.priceQueryModel.predictBulkOrderTime = content;
                break;
            }
            case 4: {
                self.priceQueryModel.predictPerOrderNumber = content;
                break;
            }
            case 5: {
                self.priceQueryModel.isChoiceMainfabric = [content isEqualToString:@"是"]?@"1":@"0";
                break;
            }
            default:
                break;
        }
    }
    if (indexPath.section == 2) {
        switch (indexPath.row) {
            case 0: {
                self.priceQueryModel.storeAddress = content;
                break;
            }
            case 1: {
                self.priceQueryModel.productDetailRequire = content;
                break;
            }
            default:
                break;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return section == 0?13:10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.priceTitle isEqualToString:@"制版打样"]) {
        if (indexPath.section == 1 && indexPath.row == 4) {
            return 0;
        }
    }
    if ([self.priceTitle isEqualToString:@"询价单"]) {
        if (indexPath.section == 1 && indexPath.row == 2) {
            return 0;
        }
    }
    return indexPath.section == 3?70:44;
}


@end
